package com.eedi.framework.oauth2.convert;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.eedi.framework.common.core.KeyValue;
import com.eedi.framework.common.enums.UserTypeEnum;
import com.eedi.framework.common.util.collection.CollectionUtils;
import com.eedi.framework.common.util.object.BeanUtils;
import com.eedi.framework.oauth2.controller.sys.vo.open.SysOAuth2OpenAccessTokenResp;
import com.eedi.framework.oauth2.controller.sys.vo.open.SysOAuth2OpenAuthorizeInfoResp;
import com.eedi.framework.oauth2.dal.dataobject.SysOAuth2AccessTokenDO;
import com.eedi.framework.oauth2.dal.dataobject.SysOAuth2ApproveDO;
import com.eedi.framework.oauth2.dal.dataobject.SysOAuth2ClientDO;
import com.eedi.framework.security.core.util.SecurityFrameworkUtils;
import com.eedi.framework.oauth2.controller.sys.vo.open.SysOAuth2OpenCheckTokenResp;
import com.eedi.framework.oauth2.util.OAuth2Utils;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Mapper
public interface SysOAuth2OpenConvert {

    SysOAuth2OpenConvert INSTANCE = Mappers.getMapper(SysOAuth2OpenConvert.class);

    default SysOAuth2OpenAccessTokenResp convert(SysOAuth2AccessTokenDO bean) {
        SysOAuth2OpenAccessTokenResp respVO = BeanUtils.toBean(bean, SysOAuth2OpenAccessTokenResp.class);
        respVO.setTokenType(SecurityFrameworkUtils.AUTHORIZATION_BEARER.toLowerCase());
        respVO.setExpiresIn(OAuth2Utils.getExpiresIn(bean.getExpiresTime()));
        respVO.setScope(OAuth2Utils.buildScopeStr(bean.getScopes()));
        return respVO;
    }

    default SysOAuth2OpenCheckTokenResp convert2(SysOAuth2AccessTokenDO bean) {
        SysOAuth2OpenCheckTokenResp respVO = BeanUtils.toBean(bean, SysOAuth2OpenCheckTokenResp.class);
        respVO.setExp(LocalDateTimeUtil.toEpochMilli(bean.getExpiresTime()) / 1000L);
        respVO.setUserType(UserTypeEnum.MEMBER_SYS.getCode());
        return respVO;
    }

    default SysOAuth2OpenAuthorizeInfoResp convert(SysOAuth2ClientDO client, List<SysOAuth2ApproveDO> approves) {
        // 构建 scopes
        List<KeyValue<String, Boolean>> scopes = new ArrayList<>(client.getScopes().size());
        Map<String, SysOAuth2ApproveDO> approveMap = CollectionUtils.convertMap(approves, SysOAuth2ApproveDO::getScope);
        client.getScopes().forEach(scope -> {
            SysOAuth2ApproveDO approve = approveMap.get(scope);
            scopes.add(new KeyValue<>(scope, approve != null ? approve.getApproved() : false));
        });
        // 拼接返回
        return new SysOAuth2OpenAuthorizeInfoResp(
                new SysOAuth2OpenAuthorizeInfoResp.Client(client.getName(), client.getLogo()), scopes);
    }

}
